package com.qianchang.microfinance.view;


import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.FrameLayout;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.statusbar.StatusBarUtil;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.AboutInfo;
import com.qianchang.microfinance.bean.event.LoginEvent;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.setting.DownLoadingDialog;
import com.qianchang.microfinance.utils.AppManager;
import com.qianchang.microfinance.utils.AppUpdateManager;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.dialog.alert.DimengConfirmAlertDialog;
import com.qianchang.microfinance.view.findings.FindFragment;
import com.qianchang.microfinance.view.home.HomeFragment;
import com.qianchang.microfinance.view.mine.MineFragment;
import com.qianchang.microfinance.view.product.ProductFragment;
import com.qianchang.microfinance.widgets.navigatetab.NavigateTabBar;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity {

    private static final String TAG = "MainActivity";
    @BindView(R.id.flTabContent)
    FrameLayout flTabContent;
    @BindView(R.id.mainTabBar)
    NavigateTabBar mNavigateTabBar;
    private int mCurrentIndex;
    private int tempIndex;
    private long mExitTime;
    //    AccumulateCreditFragment.class.getName()  攒信用
    private static final String[] titles = new String[]{"首页", "产品", "我的","借钱"};
    private boolean isLoginFailed;
    private boolean isMore = false;
    private static int NEED_LOGIN_INDEX = 2;
    private DownLoadingDialog downLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        StatusBarUtil.setTranslucentForImageViewInFragment(MainActivity.this, null);
        mNavigateTabBar.onRestoreInstanceState(savedInstanceState);

        mNavigateTabBar.addTab(HomeFragment.class, new NavigateTabBar.TabParam(R.drawable.btn_sy_n, R.drawable.btn_sy_s, titles[0], false));
        if (!ConstantAppInfo.IS_ONLY_CASH) {
            mNavigateTabBar.addTab(ProductFragment.class, new NavigateTabBar.TabParam(R.drawable.btn_cp_n, R.drawable.btn_cp_s, titles[1], false));
        }
        mNavigateTabBar.addTab(FindFragment.class, new NavigateTabBar.TabParam(R.drawable.find_nor, R.drawable.find_prs, titles[3], false));
        mNavigateTabBar.addTab(MineFragment.class, new NavigateTabBar.TabParam(R.drawable.btn_wd_n, R.drawable.btn_wd_s, titles[2], true));

        if (!ConstantAppInfo.IS_ONLY_CASH) {
            NEED_LOGIN_INDEX = 2;
        } else {
            NEED_LOGIN_INDEX = 1;
        }

        initListener();
        initData();

        // 友盟SDK在统计Fragment时，需要关闭Activity自带的页面统计，
        // 然后在每个页面中重新集成页面统计的代码(包括调用了 onResume 和 onPause 的Activity)。
        MobclickAgent.openActivityDurationTrack(false);
        // 设置为U-APP场景
        MobclickAgent.setScenarioType(getApplicationContext(), MobclickAgent.EScenarioType.E_UM_NORMAL);

        mNavigateTabBar.setDefaultSelectedTab(1);       //设置默认显示哪个页面

    }

    @Override
    public void initData() {
        super.initData();
        updateApp();

    }

    private void updateApp() {
        HttpParams params = new HttpParams();
        /**1表示安卓,2表示苹果*/
        params.put("sourceType", "1");
        params.put("userType", "0");
        show();
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.FIND_ABOUT, params, new RequestCallBack<AboutInfo>() {
            @Override
            public void onSuccess(JsonResult<AboutInfo> result) {
                dismiss();
                if (result.isReqDataSuccess()) {
                    final AboutInfo aboutInfo = result.getObject();
                    //有新版本
                    if (AppUpdateManager.needUpdate(aboutInfo)) {
                        //是否强制更新   0是1否
                        if ("1".equals(aboutInfo.getMandatoryUpdate())) {
                            DimengConfirmAlertDialog dimengButtonAlertDialog = DimengConfirmAlertDialog.newInstance("", String.format(getString(R.string.has_update_version), aboutInfo.getVersionName()));
                            dimengButtonAlertDialog.setAgreeText(getString(R.string.update_now));
                            dimengButtonAlertDialog.setOnDialogClickListener(new DimengConfirmAlertDialog.OnDialogClickListener() {
                                @Override
                                public void agree() {
                                    downLoadApp(aboutInfo, true);
                                }

                                @Override
                                public void cancel() {
                                }
                            });
                            dimengButtonAlertDialog.show(getSupportFragmentManager(), getClass().getSimpleName());
                        } else {
                            downLoadApp(aboutInfo, false);
                        }
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(MainActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });

    }

    private void downLoadApp(final AboutInfo aboutInfo, final boolean canCancel) {
        checkPermission(new CheckPermListener() {

            @Override
            public void superPermission() {
                try {
                    Bundle bundle = new Bundle();
                    //  bundle.putString("url", DMConstant.Config.BASE_URL + aboutInfo.getAppUrl());   // 2018.3.9 px
                    bundle.putString("url", DMConstant.Config.FILE_IP+aboutInfo.getAppUrl());
                    bundle.putString("version", aboutInfo.getVersion());
                    downLoadingDialog = DownLoadingDialog.newInstance(bundle);
                    downLoadingDialog.canCancel(canCancel);
                    downLoadingDialog.show(getSupportFragmentManager(), getClass().getSimpleName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void permissionSomeDeny() {

            }
        }, "", Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (null != intent) {
            setIntent(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isLoginFailed) {
            mNavigateTabBar.setCurrentSelectedTab(tempIndex);
        }

        MobclickAgent.onPageStart(TAG);             // 友盟基础指标统计，不能遗漏
//        MobclickAgent.onResume(this);   // 因为在BaseActivity 里面写了这里不需要重写，友盟基础指标统计，不能遗漏

    }

    @Override
    protected void onPause() {
        super.onPause();

        MobclickAgent.onPageEnd(TAG);             // 友盟基础指标统计，不能遗漏
//        MobclickAgent.onPause(this);            //  因为在BaseActivity 里面写了这里不需要重写，友盟基基础指标统计，不能遗漏
    }



    public void initListener() {
        mNavigateTabBar.setTabSelectListener(new NavigateTabBar.OnTabSelectedListener() {

            @Override
            public void onTabSelected(NavigateTabBar.ViewHolder holder) {
                mCurrentIndex = holder.tabIndex;
                //                if (mCurrentIndex == NEED_LOGIN_INDEX) {
                //                    if (!DMApplication.getInstance().isLogin()) {
                //                        Activity loginActivity = AppManager.getAppManager().currentActivity();
                //                        if (!(loginActivity instanceof LoginActivity)) {
                //                            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                //                            startActivity(intent);
                //                        }
                //                    } else {
                //                        mNavigateTabBar.setCurrentSelectedTab(mCurrentIndex);
                //                        tempIndex = mCurrentIndex;
                //                    }
                //                } else {
                mNavigateTabBar.setCurrentSelectedTab(mCurrentIndex);
                tempIndex = mCurrentIndex;
                //                }
            }
        });

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mNavigateTabBar.onSaveInstanceState(outState);
    }


    /**
     * 退出登录
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Logout(LoginEvent loginEvent) {
        LoginEvent.LoginStatue loginState = loginEvent.getLoginState();
        switch (loginState) {
//            case LOGIN_SUC:
//                isLoginFailed = true;
//                mCurrentIndex = 1;
//                tempIndex = mCurrentIndex;
//                break;
            case LOGIN_FAILED:
                isLoginFailed = true;
                break;
            case LOGOUT:
                mCurrentIndex = 0;
                tempIndex = mCurrentIndex;
                break;
            case LOGOUT_FIND:               //在我的借款点击推荐喜欢产品的更多选项返回的回调处理
                isLoginFailed = true;
                mCurrentIndex = 1;
                tempIndex = mCurrentIndex;
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //按两次返回退出应用程序
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtil.getInstant().show(this, getString(R.string.app_exit));
                mExitTime = System.currentTimeMillis();
            } else {
                AppManager.getAppManager().AppExit(this);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }


}






